package zzg.study.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import zzg.study.protocol.Packet;

import java.util.HashMap;
import java.util.Map;

import static zzg.study.protocol.command.Command.*;

/**
 * @Classname IMHandler
 * @Description 合并平行的handler,每次decode出来的指令对象只会在一个handler上进行处理
 * @Date 2023/12/9 22:33
 * @Author zhuzhenguo
 */
@ChannelHandler.Sharable
public class IMHandler extends SimpleChannelInboundHandler<Packet> {

    public static final IMHandler INSTANCE = new IMHandler();

    /**
     * 定义一个map存放指令 -> 指令处理器 的映射
     */
    private Map<Byte, SimpleChannelInboundHandler<? extends Packet>> handlerMap;

    private IMHandler() {
        handlerMap = new HashMap<>();

        handlerMap.put(MESSAGE_REQUEST, MessageRequestHandler.INSTANCE);
        handlerMap.put(CREATE_GROUP_REQUEST, CreateGroupRequestHandler.INSTANCE);
        handlerMap.put(JOIN_GROUP_REQUEST, JoinGroupRequestHandler.INSTANCE);
        handlerMap.put(QUIT_GROUP_REQUEST, QuitGroupRequestHandler.INSTANCE);
        handlerMap.put(LIST_GROUP_MEMBERS_REQUEST, ListGroupMembersRequestHandler.INSTANCE);
        handlerMap.put(GROUP_MESSAGE_REQUEST, GroupMessageRequestHandler.INSTANCE);
        handlerMap.put(LOGOUT_REQUEST, LogoutRequestHandler.INSTANCE);
    }

    /**
     * 每次回调IMHandler的channelRead0方法的时候，都通过指令找到具体的Handler，然后调用指令handler的channelRead方法
     * 其内部会进行指令类型转换，最终调用每个指令Handler的channelRead0方法
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet packet) throws Exception {
        handlerMap.get(packet.getCommand()).channelRead(ctx, packet);
    }
}
